package com.qd.panda.service.park;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.domain.entity.carpark.CarParkChargeTimeDTO;
import com.qd.panda.mapper.park.CarParkChargeTimeMapper;
import com.qd.panda.model.CarParkChargeTime;
import com.qd.panda.service.stroke.BigDecimalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 充电计费时段
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class CarParkChargeTimeService extends BaseService<CarParkChargeTimeMapper, CarParkChargeTime> {

    private static final String PREFIX_ID = "panda_car_park_charge_time_tid_{0}";
    private static final String PREFIX_PID_LIST = "panda_car_park_charge_time_pid_{0}";

    private final RedisTemplateUtil<CarParkChargeTime> redisTemplateUtil;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public CarParkChargeTimeDTO save(CarParkChargeTimeDTO dto) {
        final CarParkChargeTime model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public CarParkChargeTimeDTO update(CarParkChargeTimeDTO dto) {
        final CarParkChargeTime historyModel = Optional.ofNullable(getById(dto.getTid())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final CarParkChargeTime model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param tid 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String tid) {
        final CarParkChargeTime model = Optional.ofNullable(getById(tid)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(tid)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(CarParkChargeTimeDTO dto) {
        final QueryWrapper<CarParkChargeTime> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param tid 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String tid) {
        boolean exists = false;
        if (StringUtils.hasLength(tid)) {
            final CarParkChargeTime model = getById(tid);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param tid 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public CarParkChargeTime getById(String tid) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, tid);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(tid), CarParkChargeTime.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param tid 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public CarParkChargeTimeDTO getByIdDto(String tid) {
        return Optional.ofNullable(getById(tid)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public CarParkChargeTime getOne(CarParkChargeTimeDTO dto) {
        final QueryWrapper<CarParkChargeTime> queryWrapper = createQueryWrapper(dto);
        CarParkChargeTime model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public CarParkChargeTimeDTO getOneDto(CarParkChargeTimeDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<CarParkChargeTime> getList(CarParkChargeTimeDTO dto) {
        final QueryWrapper<CarParkChargeTime> queryWrapper = createQueryWrapper(dto);
        final List<CarParkChargeTime> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<CarParkChargeTimeDTO> getListDto(CarParkChargeTimeDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 查询当前充电站的收费时段信息
     *
     * @param pid 停车场ID
     * @return 时段列表
     */
    @Transactional(readOnly = true)
    public List<CarParkChargeTimeDTO> getListByPId(String pid) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_PID_LIST, pid);
        final List<CarParkChargeTime> l = redisTemplateUtil.getList(new CacheKey().setKey(key), () -> {
            QueryWrapper<CarParkChargeTime> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("p_id", pid);
            queryWrapper.orderByAsc("start_time");
            final List<CarParkChargeTime> list = super.list(queryWrapper);
            queryWrapper.clear();
            return list;
        }, CarParkChargeTime.class);
        if (null == l || l.isEmpty()) {
            return Collections.emptyList();
        }
        LocalTime currentLocalTime = LocalTime.now();
        return l.stream().map(carParkChargeTime -> {
            final CarParkChargeTimeDTO carParkChargeTimeDTO = modelToDto(carParkChargeTime);
            carParkChargeTimeDTO.setCurrentTime(isIn(currentLocalTime, carParkChargeTimeDTO) ? ConstantDto.SF1 : ConstantDto.SF0);
            return carParkChargeTimeDTO;
        }).collect(toList());
    }

    /**
     * 充电站当前时段收费信息
     *
     * @param pid 停车场ID
     * @return 当前时段
     */
    @Transactional(readOnly = true)
    public CarParkChargeTimeDTO getCurrentTimeByPid(String pid) {
        final List<CarParkChargeTimeDTO> list = getListByPId(pid);
        if (list.isEmpty()) {
            return null;
        }
        return list.stream().filter(carParkChargeTimeDTO -> carParkChargeTimeDTO.getCurrentTime().equals(ConstantDto.SF1)).findFirst().orElse(null);
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(CarParkChargeTime model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getTid()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_PID_LIST, model.getPId()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public CarParkChargeTimeDTO modelToDto(CarParkChargeTime model) {
        if (null == model) {
            return null;
        }
        final CarParkChargeTimeDTO dto = new CarParkChargeTimeDTO();
        dto.setTid(model.getTid());
        dto.setOriginalPrice(model.getOriginalPrice());
        dto.setConcessionalRate(model.getConcessionalRate());
        dto.setServiceCharge(model.getServiceCharge());
        dto.setElectricityFees(model.getElectricityFees());
        dto.setStartTime(model.getStartTime());
        dto.setEndTime(model.getEndTime());
        dto.setPId(model.getPId());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public CarParkChargeTime dtoToModel(CarParkChargeTimeDTO dto) {
        if (null == dto) {
            return null;
        }
        final CarParkChargeTime model = new CarParkChargeTime();
        model.setTid(dto.getTid());
        model.setOriginalPrice(dto.getOriginalPrice());
        model.setConcessionalRate(dto.getConcessionalRate());
        model.setServiceCharge(dto.getServiceCharge());
        model.setStartTime(dto.getStartTime());
        model.setEndTime(dto.getEndTime());
        model.setPId(dto.getPId());
        model.setElectricityFees(dto.getElectricityFees());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(CarParkChargeTimeDTO dto) {
        if (null != dto.getServiceCharge()) {
            dto.setServiceChargeDisplay(BigDecimalUtil.buildDefaultScale(dto.getServiceCharge()).toPlainString());
        }
        if (null != dto.getConcessionalRate()) {
            dto.setConcessionalRateDisplay(BigDecimalUtil.buildDefaultScale(dto.getConcessionalRate()).toPlainString());
        }
        if (null != dto.getElectricityFees()) {
            dto.setElectricityFeesDisplay(BigDecimalUtil.buildDefaultScale(dto.getElectricityFees()).toPlainString());
        }
        if (null != dto.getOriginalPrice()) {
            dto.setOriginalPriceDisplay(BigDecimalUtil.buildDefaultScale(dto.getOriginalPrice()).toPlainString());
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<CarParkChargeTimeDTO> modelToDtoList(List<CarParkChargeTime> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<CarParkChargeTime> dtoToModelList(List<CarParkChargeTimeDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<CarParkChargeTime> createQueryWrapper(CarParkChargeTimeDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<CarParkChargeTime> createQueryWrapper(CarParkChargeTimeDTO dto, String tableAlias) {
        final QueryWrapper<CarParkChargeTime> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias)) {
                if (tableAlias.charAt(tableAlias.length() - 1) != '.') {
                    tableAlias += ".";
                }
            }
            if (StringUtils.hasLength(dto.getPId())) {
                queryWrapper.eq(tableAlias + "p_id", dto.getPId());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     */
    public List<CarParkChargeTime> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<CarParkChargeTime> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(CarParkChargeTime::getTid).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    /**
     * 判断传入时间是否在时段内
     *
     * @param currentLocalTime     传入时间
     * @param carParkChargeTimeDTO 时段
     * @return true or false
     */
    private boolean isIn(LocalTime currentLocalTime, CarParkChargeTimeDTO carParkChargeTimeDTO) {
        return carParkChargeTimeDTO.getStartTime().isBefore(currentLocalTime) && carParkChargeTimeDTO.getEndTime().isAfter(currentLocalTime);
    }
}